package com.sinoglobal.ningxia.service;

import com.sinoglobal.ningxia.R;
import com.sinoglobal.ningxia.activity.mico.BroadCastActivity;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.PluginState;

/**
 * @author qiwx
 * @createdate 2014-7-29 上午9:11:48
 * @Description: 播放广播服务
 */
public class RadioService extends Service {
	private WebView player;// 广播播放，调用新浪电台url进行播放
	private WebSettings settings;
	private int playState;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();

	}

	@Override
	public void onDestroy() {
		Log.i("dd", "serviceDestory");
		try {
			player.destroy();
			player.loadUrl(null);
			player.pauseTimers();
			player.stopLoading();
		} catch (Exception e) {
			e.printStackTrace();
		}

		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent != null) {
			String url = intent.getStringExtra("radioUrl");
			playState = intent.getIntExtra("flag", 0);
			if (playState == 1) {
				try {
					Log.i("dd", "1111" + url);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (playState == 2) {
				try {
					player.loadUrl(url);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (playState == 0) {

			}

		}

		// player.loadUrl("http://wx.qingting.fm/channels/1839");
		return super.onStartCommand(intent, flags, startId);
	}

	// 初始化WebView
	private void initWebView() {

		settings.setJavaScriptEnabled(true);
		settings.setPluginState(PluginState.ON);
		// 监听webview加载进度
		player.setWebChromeClient(new MyWebChromeClient());

		player.setWebViewClient(new MyWebViewClient());

	}

	class MyWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return false;
		}

	}

	class MyWebChromeClient extends WebChromeClient {

		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			super.onProgressChanged(view, newProgress);
			if (newProgress == 100) {
				/*Intent go = new Intent();
				go.setAction(BroadCastActivity.RADIO_PROGRESS);
				go.putExtra("flag", 1);
				sendBroadcast(go);*/
				// pb.setVisibility(View.GONE);
			} else {
				// pb.setVisibility(View.VISIBLE);
			}
		}

	}

}
